import os
import json
from pdf_watermarker import PdfWatermarker
from pdf_to_png_converter import PdfToPngConverter
from wechat_publisher import WechatPublisher


def load_config():
    """加载配置文件"""
    config_path = os.path.join(os.path.dirname(__file__), 'config.json')
    try:
        with open(config_path, 'r', encoding='utf-8') as f:
            return json.load(f)
    except FileNotFoundError:
        raise Exception("请创建config.json文件并配置微信公众号信息")


def process_pdfs():
    """
    处理PDF文件：添加水印，转换为PNG图片，发布到微信公众号
    """

    # 调用pdf_watermarker为pdf文件添加水印
    pdf_watermarker = PdfWatermarker()
    pdf_watermarker.process_folder()

    # 调用pdf_to_png_converter将打完水印的pdf文件转化为png格式
    pdf_folder_path = pdf_watermarker.output_folder     # 获取存放pdf的文件夹
    pdf_to_png_converter = PdfToPngConverter(pdf_folder_path)
    pdf_to_png_converter.process_folder()

    # 调用wechat_publisher将已经处理过的图片批量上传到微信公众号
    config_info = load_config()
    wechat_publisher = WechatPublisher(config_info['appid'], config_info['secret'], pdf_folder_path)
    wechat_publisher.create_draft_batch(config_info['media_id'], pdf_folder_path)


if __name__ == '__main__':
    process_pdfs()
